package com.cashg.activity;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.cashg.R;
import com.cashg.cursoradapter.MainViewCursorAdapter;
import com.cashg.dao.CashGEntities;

public class MainActivity extends Activity {

	Cursor cur;
	LinearLayout root ;
	SimpleCursorAdapter mAdapter;
	LinearLayout listLayout ;
	MyObserver contentObserver = new MyObserver();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_view);
		getContentResolver().registerContentObserver(CashGEntities.Merchant.MERCHANT_URI, true, contentObserver);
		//cur.setNotificationUri(getContentResolver(), CashGEntities.Merchant.MERCHANT_URI);
		refresh();
	}
	
	private void refresh() {

		
		Cursor cursor = query();
		cursor.setNotificationUri(getContentResolver(), CashGEntities.Merchant.MERCHANT_URI);
		
		MainViewCursorAdapter adapter = new MainViewCursorAdapter(this, R.layout.main_view_list_item, cursor, true);
		
		ListView listView = (ListView) findViewById(R.id.mainList);
		listView.setAdapter(adapter);
	}

	@SuppressLint(value = { "" })
	class MyObserver extends ContentObserver {		
	   public MyObserver() {
	      super(null);			
	   }

	   @Override
	   public void onChange(boolean selfChange) {
		  System.out.print("HI changed");
	      this.onChange(selfChange, null);
	   }		

	   @Override
	   public void onChange(boolean selfChange, Uri uri) {
	      // do s.th.
	      // depending on the handler you might be on the UI
	      // thread, so be cautious!
	   }		
	}	
	
	private Cursor query() {

            Uri queryUri = CashGEntities.Merchant.MERCHANT_URI;
                   
            
            Cursor c = getContentResolver().query(queryUri, null, null, null, null);
            return c;
            //mAdapter.changeCursor(c);
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		MenuItem menuItem = menu.add("Refresh");
		menuItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener(){

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				refresh();
				return true;
			}});
		
		
		return true;
	}
	
}
